// ! https://echarts.apache.org/zh/builder.html 在线定制网址 注:不能点代码压缩 比如去下面的专业地址压缩.
// ! https://www.css-js.com/ echarts 代码压缩 地址 注:不能点es6转es5.得让小程序工具自己去压缩
import Taro, { Component } from "@tarojs/taro";
// import React, { Component } from 'react'
import { View, Button } from "@tarojs/components";
import * as echarts from "../../components/ec-canvas/echarts";
import "./index.css";
export default class Bar extends Component {
  config = {
    navigationBarTitleText: "柱状图示例",
    usingComponents: {
      "ec-canvas": "../../components/ec-canvas/ec-canvas"
    }
  };
  componentDidMount() {
    const chartData = {
      dimensions: {
        data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
      },
      measures: [
        {
          data: [10, 52, 200, 334, 390, 330, 220]
        }
      ]
    };

    // TODO 这里延迟2s 因为页面初始化的时候 echart 还没准备好 init会抛出错误 所以延迟2s 在更新数据时就不用延迟2s
    // setTimeout(() => {
    this.refresh(chartData);
    // }, 2000);
  }
  constructor(props) {
    super(props);
  }

  state = {
    ec: {
      lazyLoad: true
    }
  };

  changeEchar() {
    const chartData2 = {
      dimensions: {
        data: ["嗷呜", "狗子", "帽子", "陶华", "直井", "稀薄", "利亚"]
      },
      measures: [
        {
          data: [88, 22, 152, 82, 400, 310, 250]
        }
      ]
    };
    this.refresh(chartData2);
  }

  setChartData(chart, data) {
    //  ! 配置内容
    let option = {
      tooltip: {},
      color: ["#3398DB"],
      xAxis: [
        {
          type: "category",
          data: [],
          axisTick: {
            alignWithLabel: true
          }
        }
      ],
      yAxis: [
        {
          type: "value"
        }
      ],
      series: []
    };
    if (data && data.dimensions && data.measures) {
      option.xAxis[0].data = data.dimensions.data;
      option.series = data.measures.map(item => {
        return {
          ...item,
          type: "bar"
        };
      });
    }
    chart.setOption(option);
  }

  // 渲染
  refresh(data) {
    this.Chart.init((canvas, width, height) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      this.setChartData(chart, data);
      return chart;
    });
  }
  refChart = node => {
    this.Chart = node;
  };

  render() {
    return (
      <View className="bar-chart">
        <Button
          onClick={e => {
            this.changeEchar();
          }}
        >
          改变数据视图
        </Button>
        <ec-canvas
          ref={this.refChart}
          canvas-id="mychart-area"
          ec={this.state.ec}
        />
      </View>
    );
  }
}
